package com.zhss.demo.concurrent;

import java.util.concurrent.CountDownLatch;

/**
 * CountDownLatch小例子
 */
public class CountDownLatchDemo {
    public static void main(String[] args) throws Exception{
        /**
         * 1、CountDownLatch未出现之前，实现线程同步阻塞主要使用的是Thread.join()
         * 2、CountDownLatch在初始化的时候，实际上是将AQS中的state的值设置成2
         */
        CountDownLatch latch = new CountDownLatch(2); //
        new Thread(()->{
            try {
                Thread.sleep(1000);
                System.out.println("线程1开始执行，休眠2秒..........");
                Thread.sleep(1000);

                System.out.println("线程1准备执行CountDownLatch操作..........");
                latch.countDown();

                System.out.println("线程1完成执行CountDownLatch操作..........");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }) .start();

        new Thread(()->{
            try {
                Thread.sleep(1000);
                System.out.println("线程2开始执行，休眠2秒..........");
                Thread.sleep(1000);

                System.out.println("线程2准备执行CountDownLatch操作..........");
                latch.countDown();

                System.out.println("线程2完成执行CountDownLatch操作..........");

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }) .start();

        System.out.println("main线程准备执行CountDownLatch的await操作，将会同步阻塞等待.......");
        latch.await();
        System.out.println("所有线程都完成CountDownLatch操作，main线程的await阻塞等待结束");
    }
}
